import React from 'react';
import utils from 'utils';
import ListEmpty from 'atComponents/ListEmpty';
import ListLoading from 'atComponents/ListLoading';
import exceed from 'utils/apimap';
import { Section } from '@alife/devops-ui';
import { ORGANIZATION_ADMIN_ROLES } from 'utils/constants.js';
import { access } from 'components/accessContainer/util';
import { navigate } from 'utils/router';
import docs from 'utils/docs';
import intl from '../../../../../../../../../../locale';

const SUCCESS = 2;
const FAIL = 3;
const backupStatusMap = {
  [SUCCESS]: intl.get({ id: 'code-assets.containers.backup.Success', defaultMessage: '成功' }),
  [FAIL]: intl.get({ id: 'code-assets.containers.backup.Failed', defaultMessage: '失败' }),
};

export default class Record extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoading: true,
      data: {},
    };
  }

  componentDidMount() {
    this.getData();
  }

  getData = () => {
    this.setState({
      isLoading: false,
    });

    const { pathResource } = window.FORCE;
    exceed
      .fetch({
        api: 'repo.backup.info',
        params: {
          projectId: pathResource.id,
        },
      })
      .then((result) => {
        this.setState({
          isLoading: false,
          data: result,
        });
      })
      .fail((err) => {
        console.error(err);
        this.setState({
          isLoading: false,
        });
      });
  };

  goOrgBackupPage = () => {
    navigate('/settings/repository_back_up');
  };

  render() {
    const { isLoading, data } = this.state;

    if (isLoading) {
      return <ListLoading />;
    }
    const { is_enable_back_up, back_up_logs = [] } = data;
    const isOrgAdmin = access(ORGANIZATION_ADMIN_ROLES, window.FORCE.organization.user_role);

    return (
      <div className="backup-container">
        <Section
          title={intl.get({
            id: 'code-assets.containers.backup.BackupService',
            defaultMessage: '备份服务',
          })}
          description={intl.get({
            id: 'code-assets.containers.backup.YouCanBackUpRepositories',
            defaultMessage: '支持将仓库备份至指定存储空间',
          })}
        >
          <div className="backup-container-state">
            <div className={`backup-state-dot ${is_enable_back_up ? 'green' : ''}`} />
            <div className="backup-state-desc">
              {is_enable_back_up
                ? intl.get({
                    id: 'code-assets.containers.backup.BackupServiceEnabled',
                    defaultMessage: '备份服务已启用',
                  })
                : intl.get({
                    id: 'code-assets.containers.backup.TheBackupServiceIsNot',
                    defaultMessage: '备份服务未启用',
                  })}
            </div>
            <a className="backup-state-docs" href={docs('backup')} target="_blank" rel="noreferrer">
              {is_enable_back_up
                ? intl.get({
                    id: 'code-assets.containers.backup.LearnMore',
                    defaultMessage: '了解更多',
                  })
                : intl.get({
                    id: 'code-assets.containers.backup.HowToEnable',
                    defaultMessage: '如何启用',
                  })}
            </a>
          </div>
        </Section>
        <Section
          title={intl.get({
            id: 'code-assets.containers.backup.BackupRecords',
            defaultMessage: '备份记录',
          })}
          description={
            <div className="backup-container-desc">
              {intl.get({
                id: 'code-assets.containers.backup.TheFollowingIsTheLatest',
                defaultMessage: '以下为当前仓库最新备份情况，如需了解备份详情请',
              })}

              {isOrgAdmin ? (
                <a className="no-href-with-click" onClick={this.goOrgBackupPage}>
                  {intl.get({
                    id: 'code-assets.containers.backup.ViewEnterpriseSettings',
                    defaultMessage: '前往企业设置查看',
                  })}
                </a>
              ) : (
                intl.get({
                  id: 'code-assets.containers.backup.ContactTheEnterpriseAdministrator',
                  defaultMessage: '联系企业管理员',
                })
              )}
            </div>
          }
        >
          <div className="backup-container-record">
            {back_up_logs.length === 0 ? (
              <ListEmpty
                size="small"
                type="card"
                content="暂无记录"
                image="none"
                className="no-content no-btns"
              />
            ) : (
              <div className="record-detail">
                {back_up_logs.map((log) => {
                  return (
                    <div>
                      <div className="record-detail-item">
                        <div>
                          {intl.get({
                            id: 'code-assets.containers.backup.LastBackupTime',
                            defaultMessage: '最近备份时间：',
                          })}
                        </div>
                        <div>{utils.getBeautyTime(log.gmt_modified)}</div>
                      </div>
                      <div
                        className={`record-detail-item ${
                          log.status === SUCCESS ? 'success' : 'danger'
                        }`}
                      >
                        <div>
                          {intl.get({
                            id: 'code-assets.containers.backup.LatestBackupStatus',
                            defaultMessage: '最近备份状态：',
                          })}
                        </div>
                        <div className="record-detail-item-state">
                          {backupStatusMap[log.status]}
                        </div>
                      </div>
                      {log.status === FAIL && (
                        <div className="record-detail-item">
                          <div>
                            {intl.get({
                              id: 'code-assets.containers.backup.CauseOfFailure',
                              defaultMessage: '失败原因：',
                            })}
                          </div>
                          <div>{log.error_msg}</div>
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>
            )}
          </div>
        </Section>
      </div>
    );
  }
}
